<style rel="stylesheet/scss" lang="scss" scoped>
@import "../../../styles/prod.scss";

.upload-df {
  vertical-align: top;
  margin-right: 10px;
}

.upload-img {
  padding: 0;
}

.dialog-footer {
  text-align: right;
  padding-top: 20px;
}
</style>
<template>
  <div class="app-container calendar-list-container">
    <div v-if="!productDialog.visible">
      <!-- 基本属性 -->
      <custom-card title="报价单内容填写" class="mt-30">
        <template>
          <basic-form
            :basicInfo="basicForm"
            :ruleForm="detail.pdsFileModelBaseDto"
            ref="basicForm"
            :lang="language"
          ></basic-form>
          <el-button
            type="success"
            size="small"
            v-if="detail.productList.length <1"
            @click="addProduct()"
          >添加产品</el-button>
          <el-table :data="detail.productList" border style="width: 100%">
            <el-table-column label="序号" width="60px" align="center">
              <template slot-scope="scope">{{scope.$index+1}}</template>
            </el-table-column>
            <el-table-column prop="pdsFileModelBaseDto.name" label="产品名称" align="center"></el-table-column>
            <el-table-column label="产品规格" align="center">
              <template slot-scope="scope">
                <el-input :disabled="true" v-model="scope.row.productStandard" placeholder="产品规格"></el-input>
              </template>
            </el-table-column>
            <el-table-column label="标准工时" align="center">
              <template slot-scope="scope">
                <el-input
                  :disabled="true"
                  v-model="scope.row.standardWorkingHours"
                  placeholder="标准工时"
                ></el-input>
              </template>
            </el-table-column>
            <el-table-column prop="pdsFileModelBaseDto.plmModelNo" label="参考型号" align="center"></el-table-column>
            <el-table-column label="预计订单数量" align="center">
              <template slot-scope="scope">
                <el-input
                  :disabled="true"
                  v-model="scope.row.estimatedOrderQuantity"
                  placeholder="预计订单数量"
                ></el-input>
              </template>
            </el-table-column>
            <el-table-column label="单位" align="center">
              <template slot-scope="scope">
                <el-select :disabled="true" v-model="scope.row.unitDv" placeholder="单位">
                  <el-option
                    v-for="item in dict.comm_unit"
                    :key="item.id"
                    :label="item.labelDefault"
                    :value="item.value"
                  ></el-option>
                </el-select>
              </template>
            </el-table-column>
            <el-table-column prop="fullCost" label="全成本" align="center"></el-table-column>
            <el-table-column prop="profitRate" label="利润率%" align="center"></el-table-column>
            <el-table-column prop="realQuote" label="实际报价" align="center"></el-table-column>
            <el-table-column label="操作" width="250px" fixed="right" align="center">
              <template slot-scope="scope">
                <el-button-group>
                  <el-button
                    class="filter-item"
                    type="primary"
                    @click="addProduct(scope.$index)"
                    size="mini"
                  >产品查看</el-button>
                  <!-- <el-button class="filter-item" type="success" @click="ajustPrice(scope.$index)" size="mini">价格调整
                  </el-button>-->
                </el-button-group>
              </template>
            </el-table-column>
          </el-table>
          <custom-card title="报价条件">
            <!-- <el-button type="success" size="small" @click="addPrice()">添加报价条件</el-button>
            <el-table :data="detail.priceCondition" border style="width: 100%">
              <el-table-column label="序号" width="60px" align="center">
                <template slot-scope="scope">
                  {{scope.$index+1}}
                </template>
              </el-table-column>
              <el-table-column label="条件项" width="200px" align="center">
                <template slot-scope="scope">
                  <el-select v-model="scope.row.condition" placeholder="请选择">
                    <el-option v-for="item in conditionList" :key="item.id"
                               :label="language=='en'?item.labelEnUs:item.labelZhCh" :value="item.id">
                    </el-option>
                  </el-select>
                </template>
              </el-table-column>
              <el-table-column label="条件内容" align="center">
                <template slot-scope="scope">
                  <el-input v-model="scope.row.content" placeholder="请输入条件内容" required></el-input>
                </template>
              </el-table-column>
              <el-table-column prop="" label="操作" width="120px" align="center">
                <template slot-scope="scope">
                  <el-button class="filter-item" type="danger" @click="deletePrice(scope.$index)" size="mini">删除
                  </el-button>
                </template>
              </el-table-column>
            </el-table>-->
            <el-row class>
              <!-- <el-col :span="6">
            <el-input placeholder="输入关键字进行过滤" v-model="data.asset">
            </el-input>
            <el-tree class="filter-tree" :data="data.assetTreeList" default-expand-all @node-click="handleTreeClick"
                     :filter-node-method="filterAsset" ref="treeAsset">
            </el-tree>
              </el-col>-->
              <el-col :span="24" style="padding-left:20px">
                <el-table :data="data.showAccessoriesList" border style="width: 100%">
                  <el-table-column label="序号" width="60px" type="index" align="center">
                    <template slot-scope="scope">{{scope.$index+1}}</template>
                  </el-table-column>
                  <el-table-column label="条件项" width>
                    <template
                      slot-scope="scope"
                    >{{language=='en'?scope.row.nameEn:scope.row.nameCn}}</template>
                  </el-table-column>
                  <el-table-column label="条件内容" width="200px" align="center">
                    <template slot-scope="scope">
                      <el-input :disabled="true" v-model="scope.row.conditionContext"></el-input>
                    </template>
                  </el-table-column>
                  <!-- <el-table-column label="操作" width="100px" align="center">
                <template slot-scope="scope">
                  <el-button class="filter-item" type="danger" size="mini"
                             @click="deletItem(scope.$index,data.showAccessoriesList)">删除
                  </el-button>
                </template>
                  </el-table-column>-->
                </el-table>
              </el-col>
            </el-row>
          </custom-card>
          <custom-card title="其他" class="mt-30">
            <template>
              <basic-form
                :basicInfo="controlForm"
                :ruleForm="detail.pdsQuoteOther"
                ref="basicForm"
                :lang="language"
              ></basic-form>
              <el-checkbox :disabled="true" v-model="detail.pdsQuoteOther.declaration">
                The above price is net price and do not include any commssion,third
                party test cost,inspection cost etc.
              </el-checkbox>
            </template>
          </custom-card>
          <custom-card title="BOM未估价料件清单" class="mt-30">
            <template>
              <el-table
                :data="detail.bomList.filter(item => item.materialNo === 'MISC')"
                border
                style="width: 100%"
              >
                <el-table-column fixed="left" label="序号" width="60px" type="index" align="center">
                  <template slot-scope="scope">{{scope.$index+1}}</template>
                </el-table-column>
                <el-table-column label="料号" prop="materialNo" width="200px" align="center"></el-table-column>
                <el-table-column label="品名" prop="materialName" width="200px" align="center"></el-table-column>
                <el-table-column label="规格" prop="materialStandard" align="center"></el-table-column>
                <el-table-column label="单位" prop="unitDv" align="center"></el-table-column>
                <el-table-column label="数量" prop="quantity" align="center"></el-table-column>
                <el-table-column label="图片" prop="materialPictureId" align="center">
                  <template slot-scope="scope">
                    <el-button
                      class
                      type="success"
                      size="mini"
                      @click="previewImg(scope.row.pictureList)"
                    >查看</el-button>
                  </template>
                </el-table-column>
                <el-table-column label="属性" prop="attribute" align="center"></el-table-column>
                <el-table-column label="产品克重" prop="productGramWeight" align="center"></el-table-column>
                <el-table-column label="模穴数" prop="cavityNumber" align="center"></el-table-column>
                <el-table-column label="机台吨位" prop="machineTonnage" align="center"></el-table-column>
                <el-table-column label="出模周期" prop="moldCycle" align="center"></el-table-column>
                <el-table-column label="说明" prop="instructions" width="200px" align="center"></el-table-column>
                <el-table-column fixed="right" label="单价" prop="price" align="center">
                </el-table-column>
                <el-table-column fixed="right" label="币种" width="120px" align="center">
                  <template slot-scope="scope">
                    <el-select :disabled="true" v-model="scope.row.currencyDv" placeholder="币种">
                      <el-option
                        v-for="item in dict.comm_currency"
                        :key="item.id"
                        :label="item.labelDefault"
                        :value="item.value"
                      ></el-option>
                    </el-select>
                  </template>
                </el-table-column>
              </el-table>
            </template>
          </custom-card>
        </template>
      </custom-card>
      <div class="pds-btm mt-30">
        <div class="right">
          <el-button
            class="filter-item"
            type="primary"
            @click="submitForm('save')"
            :loading="loading"
          >关闭</el-button>
        </div>
      </div>
    </div>
    <!-- 添加产品 -->
    <div v-show="productDialog.visible">
      <!-- <el-input style="width: 200px;" class="filter-item" placeholder="选择参考产品型号" v-model="search.context"></el-input>
      <el-button class="filter-item" type="primary" icon="search" @click="importModel()" size="small">查询</el-button>-->
      <prod-file ref="prodfile" page="detail" v-show="productDialog.product.pdsFileModelBaseDto"></prod-file>
      <div class="dialog-footer">
        <el-button @click="productDialog.visible = false" size="small">取 消</el-button>
        <el-button type="primary" @click="chooseProduct()" size="small">确 定</el-button>
      </div>
    </div>
    <img-list
      v-model="imgData.dialogVisible"
      :img-list="imgData.imgArr"
      :img-index="imgData.imgIndex"
    ></img-list>
  </div>
</template>
<script>
import { mapGetters } from "vuex";
import BasicForm from "@/components/BasicForm/index";
import * as baseApi from "@/api/common/index";
import * as addApi from "@/api/product/model/add";
import * as researchApi from "@/api/sale/research/index";
import ProdFile from "./components/prodFile";

export default {
  name: "newQuotation",
  components: {
    BasicForm,
    ProdFile
    // 'depart-selector': () =>
    //   import ('./components/departSelector')
  },
  data() {
    return {
      productDialog: {
        visible: false,
        index: null,
        product: {}
      },
      imgData: {
        dialogVisible: false,
        imgArr: [],
        imgIndex: 0
      },
      loading: false,
      search: {
        importType: "参考型号"
      },
      detail: {
        pdsFileModelBaseDto: {},
        pdsQuoteOther: {
          declaration: false
        },
        productList: [], // 添加产品
        priceCondition: [], // 报价条件
        bomList: []
      },
      conditionList: [
        {
          id: 1,
          labelZhCh: "交易条件"
        },
        {
          id: 2,
          labelZhCh: "交货期"
        },
        {
          id: 3,
          labelZhCh: "最小起订量"
        },
        {
          id: 4,
          labelZhCh: "装箱方式"
        },
        {
          id: 5,
          labelZhCh: "付款条件"
        },
        {
          id: 6,
          labelZhCh: "标准包装方式"
        },
        {
          id: 7,
          labelZhCh: "价格有效期"
        },
        {
          id: 8,
          labelZhCh: "影响价格因素"
        }
      ],
      controlForm: [
        {
          label: "sale.price.returnsRate",
          unit: "",
          element: "input",
          name: "returnsRate",
          type: "",
          disabled: true,
          col: 100,
          isRequired: false
        },
        {
          label: "sale.price.shelfLife",
          unit: "",
          element: "input",
          name: "shelfLife",
          type: "",
          disabled: true,
          col: 100,
          isRequired: false
        }
      ],
      basicForm: [
        {
          label: "sale.price.quoteNo",
          unit: "",
          element: "input",
          name: "quoteNo",
          type: "",
          disabled: true,
          isRequired: false,
          placeholder: " "
        },
        {
          label: "sale.price.quoteTime",
          unit: "",
          element: "input",
          name: "quoteTime",
          type: "",
          disabled: true,
          isRequired: false
        },
        {
          label: "sale.price.invalidTime",
          unit: "",
          element: "input",
          name: "invalidTime",
          type: "",
          disabled: true,
          isRequired: false
        },
        {
          label: "sale.price.customer",
          unit: "",
          element: "selectFilter",
          name: "customerId",
          type: "filter",
          disabled: true,
          isRequired: false
        },
        {
          label: "sale.price.customerName",
          unit: "",
          name: "customerName",
          element: "input",
          type: "",
          disabled: true,
          isRequired: false,
          options: [],
          placeholder: " "
        },
        {
          label: "sale.price.customerModel",
          unit: "",
          element: "input",
          name: "customerModel",
          type: "",
          isRequired: false,
          disabled: true,
          placeholder: " "
        },
        {
          label: "sale.price.adjustPriceCondition",
          unit: "",
          element: "input",
          name: "adjustPriceConditionDv",
          type: "",
          dict: "pds_customer_adjust",
          isRequired: false,
          disabled: true,
          placeholder: " "
        },
        {
          label: "sale.price.quoteType",
          unit: "",
          element: "select",
          dict: "pds_customer_offer_type",
          name: "quoteTypeDv",
          append: "",
          type: "",
          disabled: true,
          isRequired: false
        },
        {
          label: "sale.price.currency",
          unit: "",
          element: "select",
          name: "currencyDv",
          type: "",
          disabled: true,
          dict: "comm_currency",
          isRequired: false
        },
        {
          label: "sale.price.taxRate",
          unit: "",
          element: "select",
          name: "taxRateDv",
          append: "",
          dict: "pds_customer_tmp_tax",
          type: "",
          disabled: true,
          isRequired: false
        },
        {
          label: "sale.price.paymentTerms",
          unit: "",
          element: "select",
          name: "paymentTermsDv",
          type: "",
          disabled: true,
          dict: "pds_customer_payment",
          isRequired: false
        },
        {
          label: "sale.price.transportationType",
          unit: "",
          element: "select",
          name: "transportationTypeDv",
          type: "",
          disabled: true,
          dict: "pds_customer_transport",
          isRequired: false
        },
        {
          label: "sale.price.portShipment",
          unit: "",
          element: "select",
          append: "",
          name: "portShipmentDv",
          type: "",
          disabled: true,
          dict: "pds_customer_tmp_port",
          isRequired: false
        },
        {
          label: "sale.price.remark",
          unit: "",
          name: "remark",
          element: "textarea",
          type: "",
          disabled: true,
          isRequired: false
        }
      ],
      productCategory: []
    };
  },
  created() {
    this.getDict();
    this.dataInit();
    this.getPdsConfAssetTree(3);
    this.refresh();
  },
  computed: {
    ...mapGetters(["elements", "language", "dict"])
  },
  methods: {
    /* 页面刷新初始化 */
    refresh() {
      if (this.$route.query.quoteId) {
        /* 编辑 */
        this.getDetail();
        //this.clearValidate();
      }
    },

    getDetail() {
      researchApi
        .getDetail({ researchId: this.$route.query.quoteId })
        .then(res => {
          if (res.code == 200) {
            this.$set(this.detail, "pdsFileModelBaseDto", res.data);
            this.$set(this.detail, "pdsQuoteOther", res.data.pdsQuoteOther);
            this.$set(
              this.detail,
              "bomList",
              res.data.notValuationMaterialList
            );
            this.$set(
              this.data,
              "showAccessoriesList",
              res.data.pdsQuoteConditionList
            );
            const pdsProductConfigList = [];
            let basePro = {};
            let baseMou = {};
            let paramList = {};
            let resData = res.data.pdsProductConfigList;
            resData.map(itemPro => {
              basePro = {
                pdsFileModelBaseDto: {}
              };
              basePro.pdsFileModelBaseDto.plmModelNo = itemPro.plmModelNo;
              basePro.pdsFileModelBaseDto.productCategoryId =
                itemPro.productCategoryId;
              basePro.pdsFileModelBaseDto.standardWorkingHours =
                itemPro.standardWorkingHours;
              basePro.pdsFileModelBaseDto.name = itemPro.productName;
              basePro.productStandard = itemPro.productStandard;
              basePro.estimatedOrderQuantity = itemPro.estimatedOrderQuantity;
              basePro.id = itemPro.id;
              basePro.unitDv = itemPro.unitDv;
              basePro.showModules = [];
              basePro.pdsModuleBomMaterialList = [];
              basePro.pdsModuleBomMaterialList = JSON.parse(
                JSON.stringify(itemPro.pdsModuleBomMaterialList)
              );
              if (itemPro.productModuleList.length > 1) {
                itemPro.productModuleList.map(itmMou => {
                  baseMou = {};
                  baseMou.id = itmMou.id;
                  baseMou.moduleId = itmMou.moduleId;
                  baseMou.itemCode = itmMou.itemCode;
                  baseMou.itemNameCn = itmMou.itemNameCn;
                  baseMou.itemNameEn = itmMou.itemNameEn;
                  baseMou.paramsList = [];
                  if (itmMou.paramsList.length > 1) {
                    itmMou.paramsList.map(param => {
                      paramList = {};
                      paramList.id = param.id;
                      paramList.paramValue = param.paramValue;
                      paramList.paramMaxValue = param.paramMaxValue;
                      paramList.paramKey = param.paramKey;
                      paramList.paramCode = param.paramCode;
                      paramList.paramNameCn = param.paramNameCn;
                      paramList.paramNameEn = param.paramNameEn;
                      paramList.paramPromptWord = param.paramPromptWord;
                      paramList.paramRequired = param.paramRequired;
                      paramList.paramTypeDv = param.paramTypeDv;
                      paramList.paramUnitDv = param.paramUnitDv;
                      paramList.standard = param.standard;
                      baseMou.paramsList.push(paramList);
                    });
                  }
                  basePro.showModules.push(baseMou);
                });
              }
              this.detail.productList.push(basePro);
            });
            //this.$set(this.detail, 'productList',  this.deatal.productList);
            console.log("pro", this.detail.productList);
            // const setMulSelect = str => {
            //   let arr = str.split(',');
            //   arr = arr.map(row => Number(row));
            //   return arr;
            // };
            // console.log('customerIds',res.data.customerId)
            // this.$set(this.pdsFileModelBaseDto, 'customerIds', setMulSelect(res.data.customerId));
            // // /* 客户代码回显 */
            // let customerNameArr = [];
            // if (res.data.customerNames) res.data.customerNames.split(',');
            // customerNameArr.map((item, index) => {
            //   this.$refs.basicForm.getPdsCustomerByName(item);
            // })

            // this.$set(this.pdsFileModelBaseDto, 'pdsConfCategory', setMulSelect(res.data.productCategoryIds));
            // this.$set(this.pdsFileModelBaseDto, 'certsDvs', setMulSelect(res.data.certsDvs));
            // // this.$set(
            // //   this.pdsFileModelBaseDto,
            // //   'pdsFileModelPbsPicsList',
            // //   res.data.pdsPlanningModelPicsList
            // // );
            // console.log('detail', this.pdsFileModelBaseDto);
          }
        });
    },
    dataInit() {
      const data = {
        assetTreeList: [],
        showAccessoriesList: []
      };
      this.data = JSON.parse(JSON.stringify(data));
    },
    // 筛选附件
    filterAsset(value, data) {
      if (!value) return true;
      if (this.language === "en") {
        return data.nameEn.indexOf(value) !== -1;
      } else {
        return data.nameCn.indexOf(value) !== -1;
      }
    },
    // 获取附件树
    getPdsConfAssetTree() {
      researchApi
        .getPdsSaleConfAssetTree({
          type: 1
        })
        .then(res => {
          this.data.assetTreeList = res.data;
        });
    },
    // 是否是新增附件选项
    handleTreeClick(data) {
      let isNew = true;
      console.log(this.language == "en");
      this.data.showAccessoriesList.map(row => {
        if (row.assetId === data.id) {
          isNew = false;
        }
        // return row
      });
      if (isNew) {
        data.assetId = data.id;
        data.nameCn = data.nameCn;
        data.conditionContext = "";
        this.data.showAccessoriesList.push({
          assetId: data.id,
          id: data.id,
          nameCn: data.nameCn,
          nameEn: data.nameEn,
          conditionContext: data.conditionContext
        });
      }
    },
    //图片预览
    previewImg(imgArr, index) {
      this.imgData.dialogVisible = true;
      this.imgData.imgArr = imgArr;
      this.imgData.imgIndex = index || 0;
    },
    // 删除特征或者附件
    deletItem(index, list) {
      list.splice(index, 1);
    },
    addProduct(index) {
      this.productDialog.visible = true;
      if (index > -1) {
        this.productDialog.index = index;
        this.productDialog.product = JSON.parse(
          JSON.stringify(this.detail.productList[index])
        );
        this.search.context = this.productDialog.product.pdsFileModelBaseDto.plmModelNo;
      } else {
        this.productDialog.product = {};
        this.search.context = "";
      }
      console.log(this.productDialog);
      this.$refs.prodfile.refresh(
        this.productDialog.product,
        this.detail.pdsFileModelBaseDto.pdsProductConfigList[index].id
      );
    },
    async chooseProduct() {
      const moduleFormRes = await this.$refs.prodfile.submitForm();
      this.detail.bomList = moduleFormRes.bom.bomList;
      this.detail.showModules = moduleFormRes.data.showModules;
      const updataParams = JSON.parse(JSON.stringify(this.detail));
      const setModuleData = () => {
        updataParams.showModules.map(moduleItem => {
          if (moduleItem.paramsList && moduleItem.paramsList.length) {
            moduleItem.paramsList.map(paramsItem => {
              paramsItem.paramValue = moduleItem.formData[paramsItem.id];
              paramsItem.paramMaxValue =
                moduleItem.formData[paramsItem.id + "m"];
            });
          }
        });
      };
      setModuleData();
      // console.log(this.productDialog.product)
      // console.log('moduleFormRes',updataParams.showModules)
      const index = this.productDialog.index;
      this.productDialog.product.showModules = updataParams.showModules;
      if (index != null) {
        this.detail.productList[index] = JSON.parse(
          JSON.stringify(this.productDialog.product)
        );
      } else {
        this.detail.productList.push(
          JSON.parse(JSON.stringify(this.productDialog.product))
        );
      }
      this.search.context = "";
      this.productDialog = {
        visible: false,
        index: null,
        product: {}
      };
    },
    importModel() {
      addApi.importModel(this.search).then(res => {
        if (res.code === 200) {
          this.productDialog.product = res.data;
          this.$refs.prodfile.refresh(res.data);
        } else {
          this.$message.error(res.message);
        }
        // this.detail.pdsFileModelBaseDto.certsDvs=[]
      });
    },
    deletePrice(index) {
      this.detail.priceCondition.splice(index, 1);
    },
    addPrice() {
      this.detail.priceCondition.push({});
    },
    // 获取字典选项
    getDict() {
      let codes = [];
      this.basicForm.map(item => {
        if (item.dict) {
          codes.push(item.dict);
        }
      });
      codes = codes.join(",");

      baseApi.getTypesValue(codes).then(res => {
        this.basicForm.forEach(value => {
          if (value.dict) {
            this.$set(value, "options", res.data[value.dict]);
          }
        });
      });
    },
    // 提交或草稿
    async submitForm() {
      this.saveToServer();
    },
    saveToServer() {
    this.$store.dispatch("delActiveViews");
    }
  }
};
</script>
